<template>
  <div class="addMerchantBox" v-loading="loading">
    <el-button
      class="el-icon-arrow-left"
      size="mini"
      type="primary"
      style="margin-bottom:10px;"
      @click="handBackList"
    >返回</el-button>
    <el-form ref="form" :model="initial_data" :rules="rules">
      <el-form-item label="权限名字" prop="name">
        <el-input v-model="initial_data.name" style="width:300px" placeholder="请输入角色名字"></el-input>
      </el-form-item>

      <el-form-item label="上级权限" prop="pid">
            <el-tree
                v-model="initial_data.pid"
                :data="permissionList" 
                ref="tree" 
                @check-change="orgCheckChange" 
                show-checkbox 
                :check-strictly="true" 
                node-key="id"
            >
        </el-tree>
      </el-form-item>

      <el-form-item label="节点" prop="rule" style="width:100%;">
          <el-select multiple="multiple" style="width:300px" v-model="initial_data.rule" placeholder="请选择节点（可多选）">
          <el-option
            v-for="(item) in ruleList"
            :key="item.id"
            :label="item.url"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <div class="submitBtnBox">
      <el-button class="submitBtn" @click="submitFn" type="primary">确认添加</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "permission-permission-add",
  components: {},
  data() {
    return {
      initial_data: {
        //获取初始数据
        token: localStorage.getItem("user_token"), //token
        name: "",
        rule: [],
        pid: ''
      },
      selectDefault:[{ id: '0', name: '没有上级' }],
      checkAll: false,
      ruleList: [],
      permissionList: [],
      loading: false,
      rules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        pid: [{ required: true, message: "请选择上级", trigger: "blur" }],
        rule: [{ required: true, message: "请选择权限", trigger: "blur" }]
      },
      selectOrg: {
        orgsid: []
      }
    };
  },
  watch: {},
  methods: {
    getPermission(){
        this.$http.get("/web/user/permissions/list/tree", {
          params: {
            token: localStorage.getItem("user_token")
          }
        })
        .then(response => {
            if (response.data.status == "success") {
                this.permissionList = response.data.data;
                this.permissionList.push({ id: '0', label: '没有上级' })
                console.log(this.permissionList)
            }
        })
        .catch(error => {
          console.log("error:", error);
        });
    },
    //获取下拉Url节点
    getUrl() {
        
      this.$http
        .get("/web/user/url/list", {
          params: {
            token: localStorage.getItem("user_token")
          }
        })
        .then(response => {
          if (response.data.status == "success") {
            this.ruleList = response.data.data;
          }
        })
        .catch(error => {
          console.log("error:", error);
        });
    },

    handBackList() {
      this.$router.push({ name: "permissionRoles" });
    },
    orgCheckChange(data, checked, indeterminate) {
     console.log(data, '数据')
     console.log(checked, '选中状态')
     console.log(indeterminate, '子树中选中状态')
     // 获取当前选择的id在数组中的索引
     const indexs = this.selectOrg.orgsid.indexOf(data.id)
     // 如果不存在数组中，并且数组中已经有一个id并且checked为true的时候，代表不能再次选择。
     if (indexs < 0 && this.selectOrg.orgsid.length === 1 && checked) {
       console.log('only one')
       this.$message({
         message: '只能选择一个区域！',
         type: 'error',
         showClose: true
       })
       // 设置已选择的节点为false 很重要
       this.$refs.tree.setChecked(data, false)
     } else if (this.selectOrg.orgsid.length === 0 && checked) {
       // 发现数组为空 并且是已选择
       // 防止数组有值，首先清空，再push
       this.selectOrg.orgsid = []
       this.selectOrg.orgsid.push(data.id)
       this.initial_data.pid = data.id
     } else if (
       indexs >= 0 &&
       this.selectOrg.orgsid.length === 1 &&
       !checked
     ) {
       // 再次直接进行赋值为空操作
       this.selectOrg.orgsid = []
     }
   },

    submitFn() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return false;
        } else {
          this.loading = true;
          this.$nextTick(() => {
            this.$http
              .post("/web/user/permissions/add", this.initial_data)
              .then(response => {
                if (response.data.status == "success") {
                  this.$message({
                    message: "添加成功",
                    duration: 6000
                  });

                  this.$router.push({
                    name: "permission"
                  });
                } else {
                  this.$message({
                    message: "添加失败，原因：" + response.data.failedMsg,
                    duration: 6000
                  });
                }
                this.loading = false;
              })
              .catch(error => {
                this.$message({
                  message: "添加失败，原因：" + error,
                  duration: 6000
                });
                this.loading = false;
              });
          });
        }
      });
    }
  },
  mounted() {
    this.getUrl();
    this.getPermission();
  }
};
</script>

<style scoped lang="scss">
@import "./permission.scss";
</style>
